package com.tuling.stu.service;

import java.util.Calendar;
import java.util.Date;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import redis.clients.jedis.Jedis;

import com.tuling.stu.base.JedisPoolUtil;

/**
 * 大型电商交易系统高并发分布式订单号生成策略
 * @author chenhs
 * Created on 2017年12月12日 上午10:43:08
 */
@Service
public class RedisServiceImpl implements RedisService {

	@Autowired
	private JedisPoolUtil jedisPoolUtil;
	
	@Override
	public String getOrderIDPrefix(Date date) {
		Calendar c = Calendar.getInstance();
		c.setTime(date);
		int year = c.get(Calendar.YEAR);
		int day = c.get(Calendar.DAY_OF_YEAR);
		int hour = c.get(Calendar.HOUR_OF_DAY);
		
		String dayFmt = String.format("%1$03d", day);
		String hourFmt = String.format("%1$02d", hour);
		
		return (year-2000) + dayFmt + hourFmt;
	}

	@Override
	public Long orderId(String prefix) {
		Jedis jedis = jedisPoolUtil.getResource();
		String key = "tl_order_id" + prefix;
		String orderId = null;
		
		try {
			Long index = jedis.incr(key);	//00001 一个小时9万9 ;【°△°一个新发现：当key不存在时jedis.incr命令执行结果还是1  】
			orderId = prefix + String.format("%1$05d", index);
		} catch (Exception e) {
			System.out.println("生成订单号异常");
		} finally {
			if(null != jedis) {
				jedis.close();
			}
		}
		
		return Long.valueOf(orderId);
	}

	@Override
	public String id() {
		return String.valueOf(orderId(getOrderIDPrefix(new Date())));
	}

}
